package com.idbk.chargestation.app;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog.Builder;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.bean.JsonUpdate;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.service.UpdateService;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 更新管理类
 *
 * @author lupc, zhx
 */
public class ManagerUpdate {

    private Context mContext;
    //是否 显示查询版本信息的 等待对话框
    private boolean isShow = false;
    //等待对话框
    private ProgressDialog progressDialog;
    private StringRequest mRequest;

    private final static int MSG_DOWNLOAD_FINISH = 30000;
    private final static int MSG_DOWNLOAD_PROGRESS = 30001;
    private static final String FILE_NAME = "ChargeStation.apk";
    private int curProgress;
    private boolean isCancel = false;

    public ManagerUpdate(Context context, boolean isShow) {
        mContext = context;
        this.isShow = isShow;
    }

    public void checkUpdate() {
        if (isShow) {
            showCheckDialog();
        }
        mRequest = ChargeStationAPI.getVersionInfo(mResponse);
    }

    private EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonUpdate result = GsonUtils.toBean(JsonUpdate.class, response);
            if (result == null) {
                Toast.makeText(mContext, "服务器数据错误！", Toast.LENGTH_LONG).show();
            } else if (result.status == GlobalResult.OK.getStatus()) {
                result.newPath = ChargeStationURL.getRootURL() + result.newPath;
                onFinishCheck(result);
            } else {
                Toast.makeText(mContext, result.message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            if (isShow) {
                showFailedDialog();
            }
        }

        @Override
        public void onEFinish() {
            hideCheckDialog();
        }

    };

    private void hideCheckDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private void showCheckDialog() {
        progressDialog = ProgressDialog.show(
                mContext,
                null,
                "正在获取最新版本信息..",
                true,
                true,
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mRequest != null) {
                            mRequest.cancel();
                        }
                    }
                });
    }

    private void onFinishCheck(JsonUpdate infor) {
        if (haveNew(infor)) {
            showUpdateInfo(infor);
        } else {
            if (isShow) {
                showLatestDialog();
            }
        }
    }

    private boolean haveNew(JsonUpdate infor) {
        if (infor == null) {
            return false;
        }
        boolean haveNew = false;
        int versionCode = 0;
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(
                    mContext.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (versionCode < infor.versionCode) {
            haveNew = true;
        }
        return haveNew;
    }

    private void showUpdateInfo(final JsonUpdate infor) {
        String message = "发现新版本V" + infor.versionName + ",你现在要更新新版本吗?";
        if (infor.forceEnable) {
            message = "发现新版本V" + infor.versionName + ",为了不影响你的正常使用,请立即更新.";
        }
        new Builder(mContext)
                .setTitle("提示")
                .setMessage(message)
                .setNegativeButton(R.string.common_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (infor.forceEnable) {
                            System.exit(0);
                        }
                    }
                })
                .setPositiveButton("立即更新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //开始下载
                                startDownload(infor);
                            }
                        })
                .setNeutralButton("后台更新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //开始下载
                                serviceDownload(infor.newPath);
                            }
                        })
                .show();
    }

    private void serviceDownload(String url) {
        Intent intent = new Intent(mContext, UpdateService.class);
        intent.putExtra("apk_url", url);
        mContext.startService(intent);
    }

    private void showLatestDialog() {
        new Builder(mContext)
                .setMessage("已经是最新版本了")
                .setPositiveButton(R.string.common_ok, null)
                .show();
    }

    private void showFailedDialog() {
        new Builder(mContext)
                .setMessage("网络异常，无法获取新版本信息")
                .setPositiveButton(R.string.common_ok, null)
                .show();
    }

    private void startDownload(final JsonUpdate infor) {

        progressDialog = new ProgressDialog(mContext);
        progressDialog.setProgressStyle(
                ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setTitle("新版本V" + infor.versionName);
        progressDialog.setCancelable(false);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                "取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        isCancel = true;
                    }
                });
        progressDialog.setProgress(0);
        progressDialog.show();
        //
        downloadApp(infor.newPath);
    }

    private void downloadApp(final String destUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url;
                InputStream in = null;
                FileOutputStream out = null;
                HttpURLConnection conn = null;
                try {
                    url = new URL(destUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    long fileLength = conn.getContentLength();
                    in = conn.getInputStream();

                    File file = new File(
                            mContext.getExternalFilesDir(null),
                            FILE_NAME);
                    if (file.exists()) {
                        file.delete();
                    }
                    out = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    long readLength = 0L;
                    while ((len = in.read(buffer)) != -1) {
                        if (isCancel) {
                            break;
                        }
                        out.write(buffer, 0, len);
                        readLength += len;
                        curProgress = (int) (((float) readLength / fileLength) * 100);
                        handler.sendEmptyMessage(MSG_DOWNLOAD_PROGRESS);
                        if (readLength >= fileLength) {
                            handler.sendEmptyMessage(MSG_DOWNLOAD_FINISH);
                            break;
                        }
                    }
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DOWNLOAD_PROGRESS:
                    progressDialog.setProgress(curProgress);
                    break;
                case MSG_DOWNLOAD_FINISH:
                    progressDialog.dismiss();
                    File file = new File(
                            mContext.getExternalFilesDir(null),
                            FILE_NAME);
                    if (!file.exists()) {
                        Toast.makeText(mContext, "指定的路径目录文件不存在", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    installApk(file);
                    break;
                default:
                    break;
            }
        }
    };

    private void installApk(File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }


}
